﻿using AutoMapper;
using MediatR;
using MyRabbit.Application.Command;
using MyRabbit.Application.ErrorCode;
using MyRabbit.Domain;
using MyRabbit.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace MyRabbit.Application.CommandHandler
{
    public class BreedAddCommandHandler : IRequestHandler<BreedAddCommand, APIResult<object>>
    {
        /// <summary>
        /// 产品仓储
        /// </summary>
        private readonly IRepository<Product> proRep;
        /// <summary>
        /// 养殖仓储
        /// </summary>
        private readonly IRepository<Breed> breedRep;
        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="proRep">产品仓储</param>
        /// <param name="breedRep">养殖仓储</param>
        /// <param name="mapper">映射</param>
        public BreedAddCommandHandler(IRepository<Product> proRep, IRepository<Breed> breedRep,IMapper mapper)
        {
            this.mapper = mapper;
            this.proRep = proRep;
            this.breedRep = breedRep;
        }

        public async Task<APIResult<object>> Handle(BreedAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();

            result.Code = Codes.添加成功;
            result.Message = Codes.添加成功.ToString();

            using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    //添加品种
                    Breed breed = mapper.Map<Breed>(request);
                    breed.CreateTime = DateTime.Now;

                    await breedRep.InsertAsync(breed);

                    //修改产品品种
                    var data = await proRep.GetByIdAsync(request.ProductId);
                    data.BreedId = breed.BreedId;
                    await proRep.UpdateAsync(data);
                    //提交事务
                    scope.Complete();
                }
                catch (Exception exp)
                {
                    result.Code = Codes.添加失败;
                    result.Message = Codes.添加失败.ToString()+exp.Message;
                }

            }
            return await Task.FromResult(result);
        }
    }
}
